//文件系统模块

const fs = require("fs");
//整体读取文件内容
fs.readFile("04_sample.txt","utf-8",(err,data)=>{
    if(err){
        console.error(err);
    }
    else{
        console.log(data);
    }
});

//整体读取图片内容
fs.readFile("04_Evan.png",(err,data)=>{
    if(err){
        console.error(err);
    }
    else{
        console.log(data);
        console.log(data.length);
    }
});

//fs回调形式 并使用Buffer
fs.open("04_sample.txt","r",function(err,fd){
    if(err) throw err;
    console.log("打开文件...");
    let buffer = Buffer.alloc(1024);
    fs.read(fd,buffer,0,buffer.length,0,function(err,bytesRead,buffer){
        if(err) throw err;
        console.log('读取字节${bytesRead}');
        console.log(buffer.subarray(0,bytesRead).toString());
        fs.close(fd,err=>{
            if(err) throw err;
        });
    });
});

const fsPromises = fs.Promises;
(async function(file){
    let filehandle;
    try{
        filehandle = await fsPromises.open(file);
        console.log('已打开${file}文件');
        let buffer = Buffer.alloc(1024);
        console.log('读取字节${res.bytesRead}\n');
        console.log('${res.buffer.toString()}');
    }catch(error){
        console.error(error);
    }finally{
        if(filehandle){
            await filehandle.close();
        }
    }
})("04_sample.txt")

//写文件
let data = "这世界终将以我的意志前行";
fs.writeFile("04_output.txt",data,"utf-8",function(err){
    if(err){
        console.error(err);
    }else{
        console.log("写入完成");
    }
});